const Koa = require("koa");
const app = new Koa();
const render = require('koa-art-template')
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const path = require("path");
const static = require('koa-static');
const openbrw = require('./adLogin');
const { log, getLog } = require("./middleware/log");
app.use(static(path.join(__dirname + "/static")));
render(app, {
  root: path.join(__dirname, 'view'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
});
router.get('/', async function (ctx, next) {
    ctx.response.redirect('/log');
})
router.get('/log', async function (ctx, next) {
  ctx.render('log', { logs: getLog() });
  await next();
})

router.get('/logs', async function (ctx, next) {
  await next();
})
router.post('/createAd', async function (ctx, next) {
    // console.log(ctx.request.body);
    ctx.body={url:"http://"+getIPAdress()+":3000/log",runDriver:openbrw.getRunStatus()};
    openbrw.open(ctx.request.body);
    await next();
  //执行脚本文件
//   ctx.response.redirect('/log');
})
app.use(bodyParser());
app.use(router.routes());
app.use(log({}, router));
app.listen(3000);
function getIPAdress(){
  var interfaces = require('os').networkInterfaces();
  for(var devName in interfaces){
      var iface = interfaces[devName];
      for(var i=0;i<iface.length;i++){
          var alias = iface[i];
          if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
              return alias.address;
          }
      }
  }
}
console.log('server runing.....',"http://"+getIPAdress()+":3000")